<!Doctype html>
<html>
    <head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/semantic-ui/2.2.10/semantic.min.css">
		<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
		<script src="https://cdn.bootcss.com/semantic-ui/2.2.10/semantic.min.js"></script>
		<script src="https://cdn.bootcss.com/underscore.js/1.8.3/underscore-min.js"></script>
		<script src="https://cdn.bootcss.com/babel-core/6.1.19/browser.min.js"></script>
		<script src="https://cdn.bootcss.com/babel-standalone/6.22.1/babel.js"></script>
		<!-- <script src="/lib/moment-with-locales.min.js"></script> -->
		<style>
		    /* td{padding:2px;color:#666666;border:1px solid #9eccf6;white-space:nowrap;}
		       table{line-height:100%;border-collapse:collapse;} */
		</style>
    </head>
    <body>

    	<!-- containner of components -->
    	<div id="main"></div>

    	<!-- React.js UI Components -->
		<script type="text/javascript" src="/lib/fileUpload.js"></script>
		<script type="text/javascript" src="/lib/properties.js"></script>
		<script type="text/javascript" src="/lib/relFiles.js"></script>

		<!-- Main logic of this page -->
		<script type="text/javascript" src="/lib/page-import.js"></script>

    	<div class="ui main text container" style="max-width: 960px; background-color: #f9f9f9">

    		<div id="header" class="ui sticky">
			    <h2 class="ui top attached header">
				  	<span id="title"></span>
				  	<button id="commit-button" class="ui right floated button disabled">更新</button>
					<button id="upload-stat-button" class="ui right floated button" style="display:none"></button>
				  	<div class="sub header">
				  		<i class="folder icon"></i>
				  		<span id="path">路径（空）</span>
				  	</div>
				</h2>
			</div>

			

			<div id="header-below" class="ui basic segment" style="margin-top:67px">
				<div id="sys-labels" class="ui labels">暂无标签</div>
				<table class="ui very basic table">
					<!-- <thead><tr><th><i class="folder icon"></i>属性名</th><th><i class="folder icon"></i>值</th></tr></thead> -->
					<tbody id="sys-properties"></tbody>
				</table>
			</div>

			<div class="ui horizontal divider">
			    自定义属性
			</div>

			<div class="ui basic segment">
				<div class="ui">
					<div class="ui input">
						<input type="text" name="key" placeholder="属性名称">
					</div>
					<div class="ui action input">
						<input type="text" name="value" placeholder="属性值" onkeyup="return newUserPropertyFromEnter(event)">
						<button class="ui button" onclick="biggerInputArea();">更大输入框</button>
					</div>
					<div class="ui input">
						<button class="ui button primary" onclick="newUserProperty();">添加</button>
					</div>
				</div>
				<div id="user-labels" class="ui list">暂无标签</div>
				<table class="ui very basic celled table">
					<thead><tr><th><i class="folder icon"></i>属性名</th><th><i class="folder icon"></i>属性值</th><th class="collapsing floated right"></th></tr></thead>
					<tbody id="user-properties"></tbody>
				</table>


				<div id="user-tab-head" class="ui top attached tabular menu">
					<a class="item active" data-tab="comment">备注</a>
				</div>
				<div class="ui bottom attached tab segment active" data-tab="comment">
					<div class="ui form">
						<div class="field">
							<textarea id="comment"></textarea>
						</div>
					</div>
				</div>

			</div>

			<div class="ui horizontal divider">
			    相关文件
			</div>

			<div class="ui basic segment">
				<div id="file-tab-head" class="ui top attached tabular menu">
					<a class="item active" data-tab="tree-view">树状视图</a>
					<a class="item" data-tab="list-view">列表视图</a>
				</div>
				<div class="ui bottom attached tab segment active" data-tab="tree-view">
					<div id="rel-files-lst" class="ui list">
						
					</div>
				</div>
				<div class="ui bottom attached tab segment" data-tab="list-view">
					<div id="rel-files" class="ui relaxed divided list"></div>
				</div>
			</div>
		</div>


		<div id="add-property-modal" class="ui modal">
			<i class="close icon"></i>
			<div class="header">
				请输入属性
			</div>
			<div class="content">
				<div class="ui form">
					<div class="field">
						<div class="ui fluid icon input">
							<input id="key-from-modal" type="text" placeholder="属性名称">
							<i class="search icon"></i>
						</div>
					</div>
					<div class="field">
						<label>属性值</label>
						<textarea id="value-from-modal"></textarea>
					</div>
				</div>
			</div>
			<div class="actions">
				<div class="ui negative reset button" onclick="clearModalContent();">清空</div>
				<div class="ui cancel button">取消</div>
				<div class="ui positive approve right labeled icon button">
					添加
					<i class="checkmark icon"></i>
				</div>
			</div>
		</div>

		<div id="modal-warn" class="ui basic modal">
			<div class="ui icon header">
				<i class="clone icon"></i>
				属性名称重复
			</div>
			<div class="content" style="text-align: center;">
				<p>每个文件中不能包含多个相同名称的属性，请您先删除重名属性后再添加。</p>
			</div>
			<div class="actions">
				<div class="ui green ok inverted button">
					<i class="checkmark icon"></i>
					好的
				</div>
			</div>
		</div>

		<div id="correct-frame-rate" class="ui modal">
			<i class="close icon"></i>
			<div class="header">
				请选择帧率（单位：FPS）
			</div>
			<div class="content">
				<div class="ui form">
					<div class="grouped fields">
						<label for="fruit">这是由系统识别文件的帧率。如不正确，请改为正确的帧率</label>
						<div class="field">
							<div class="ui radio checkbox">
								<input type="radio" name="frameRate" tabindex="0" value="23.976" class="hidden">
								<label>23.976（常用于电影）</label>
							</div>
						</div>
						<div class="field">
							<div class="ui radio checkbox">
								<input type="radio" name="frameRate" checked="" tabindex="0" value="25" class="hidden">
								<label>25（电视，PAL制式）</label>
							</div>
						</div>
						<div class="field">
							<div class="ui radio checkbox">
								<input type="radio" name="frameRate" tabindex="0" value="29.97" class="hidden">
								<label>29.97（电视，NTSC制式）</label>
							</div>
						</div>
						<div class="field">
							<div class="ui radio checkbox">
								<input type="radio" name="frameRate" tabindex="0" value="50" class="hidden">
								<label>50</label>
							</div>
						</div>
						<div class="field">
							<div class="ui radio checkbox">
								<input type="radio" name="frameRate" tabindex="0" value="59.94" class="hidden">
								<label>59.94</label>
							</div>
						</div>
						<div class="field">
							<div class="ui radio checkbox">
								<input type="radio" name="frameRate" tabindex="0" value="other" class="hidden">
								<label>其他</label>
								<div class="ui icon input">
									<input id="frameRate-from-modal" type="text" placeholder="帧率（单位：帧数每秒）">
									<i class="file video outline icon"></i>
								</div>
							</div>
						</div>
					</div>
					
				</div>
			</div>
			<div class="actions">
				<div class="ui cancel button">取消</div>
				<div class="ui positive approve right labeled icon button">
					确定
					<i class="checkmark icon"></i>
				</div>
			</div>


		</div>

		<div id="loading" class="ui page dimmer">
			<!-- <div class="content">
			<div class="center">
			<h2 class="ui inverted icon header">
			<i class="heart icon"></i>
			Dimmed Message!
			</h2>
			</div>
			</div> -->
			<div class="ui massive text loader">提交中，請稍等（稍后自动关闭）....</div>
		</div>


    	<script type="text/template" id="user-labels-tpl">
    		<% var id = new Date().getTime(); %>
    		<div id="L-<%= id %>" class="ui label">
    			<%= key %>
    			<div class="detail"><%= value %></div>
    			<i class="delete icon" onclick="delUserLabel('L-<%= id %>');"></i>
    		</div>
		</script>

		<script type="text/template" id="sys-labels-tpl">
    		<div class="ui tag label" title="<%= key %>" data-inverted="">
    			<%= value %>
    		</div>

<!--     		<div class="ui tag label">
    			<%= key %>
    			<div class="detail"><%= value %></div>
    		</div> -->
		</script>

		<script type="text/template" id="user-properties-tpl">
			<% var id = new Date().getTime(); %>
    		<tr id="L-<%= id %>"><td class="collapsing" style="max-width: 40%"><%= key %></td><td><%= value %></td><td><i class="delete icon" onclick="delUserProperty('L-<%= id %>');"></i></td></tr>
		</script>

		<script type="text/template" id="sys-properties-tpl">
    		<tr><td class="collapsing" style="max-width: 40%"><%= key %></td><td <% if(detail){ %> title="<%= detail %>" <% } %> ><%= value %></td></tr>
		</script>

		<script type="text/template" id="rel-file-tpl">
    		<div class="item">
				<i class="large github middle aligned icon"></i>
				<div class="content">
					<a class="header"><%= name %></a>
					<div class="description"><%= path %></div>
				</div>
			</div>
		</script>
		
		<script type="text/template" id="rel-file-list-tpl">
    		<div class="item">
				<i class="<%= icon %> icon"></i>
				<div class="content">
					<div class="description"><%= name %></div>
					<div class="list"><%= children %></div>
				</div>
			</div>
		</script>

		<script type="text/template" id="user-tab-head-tpl">
			<a id="TH-<%= id %>" class="item" data-tab="t_<%= id %>"><%= key %></a>
		</script>

		<script type="text/template" id="user-tab-tpl">
			<div id="T-<%= id %>" class="ui bottom attached tab segment" data-tab="t_<%= id %>">
				<div class="ui two top attached tiny buttons">
					<button class="ui toggle button" onclick="editUserTab('<%= id %>');">编辑</button>
					<!-- <div class="or"></div> -->
					<button class="ui negative button" onclick="delUserTab('<%= id %>');">删除</button>
				</div>
				<pre class="ui attached segment" style="white-space:pre-wrap;"><%= content %></pre>
			</div>
		</script>

		<script>
			moment.locale('zh-cn')

			var fileObj = {}

		    function size2str(size){
				var sb='';
				var remain=parseInt(size);
				var oneKB=1024;
				var oneMB=oneKB*1024;
				var oneGB=oneMB*1024;
				var GB=0;
				var MB=0;
				var KB=0;
				var B=0;
				if(remain>oneGB) GB=parseInt(remain/oneGB);
				remain = remain % oneGB;
				if(remain>oneMB) MB=parseInt(remain/oneMB);
				remain = remain % oneMB;
				if(remain>oneKB) KB=parseInt(remain/oneKB);
				B = remain % oneKB;
				if(GB>0){
				    return (size/oneGB).toFixed(2)+"GB";
				}else if(MB>0){
				    if(MB>100) {
					return MB + "MB";
				    }else if(MB>10) {
					return (size/oneMB).toFixed(1)+"MB";
				    }else{
					return (size/oneMB).toFixed(2)+"MB";
				    }
				}else if(KB>0){
				    if(KB>10){
					return (size/oneKB).toFixed(1)+"KB";
				    }else{
					return (size/oneKB).toFixed(2)+"KB";
				    }
				}else{
				    return B+"Bytes";
				}

		    }

		    function getTimeZone(){
		    	var offset = new Date().getTimezoneOffset()
		    	if(offset==-480){
		    		return '北京时间'
		    	}else{
		    		var zone = offset/60
		    		return 'GMT'+(zone>0?'-':'+')+Math.abs(zone)
		    	}
		    }

		    function clearModalContent(){
		    	$('#key-from-modal').val('')
		    	$('#value-from-modal').html('')
		    }

		    function getFileExt(name){
		    	return name.slice(name.lastIndexOf('.')).toUpperCase()
		    }

		    function getFileNameFromPath(path){
		    	if(path.indexOf('\\')>=0){ //from windows
		    		return path.slice(path.lastIndexOf('\\')+1)
		    	}else{
		    		return path.slice(path.lastIndexOf('/')+1)
		    	}
		    }

		    function getFilePath(path){
		    	if(path.indexOf('\\')>=0){ //from windows
		    		return path.slice(0, path.lastIndexOf('\\'))
		    	}else{
		    		return path.slice(0, path.lastIndexOf('/'))
		    	}
		    }

		    function hashToShort(hash){
		    	if(hash.length>17){
		    		return hash.slice(0,7)+'...'+hash.slice(-7)
		    	}else{
		    		return hash
		    	}
		    }

			function groupFileByFolderIter(fileList){
				var isWindows = true
				function splitFilePath(path){
					var lst
					if(path.indexOf('\\')!=-1){
						lst = path.split('\\')
						if(lst.length>1 && lst[0]=='' && lst[1]==''){
							lst[2] = '\\\\'+lst[2]
							return _.rest(lst, 2)
						}else{
							return lst
						}
					}else{
						isWindows=false
						lst = path.split('/')
						if(lst.length>1 && lst[0]==''){
							lst[1] = '/'+lst[1]
							return _.rest(lst, 1)
						}else{
							return lst
						}
					}
				}
				function mergeTree(tree){
					var grandpa = tree
					for(var i in tree){
						var fatherKey = i
						var father = grandpa[fatherKey]
						var sonKeys = _.keys(father)
						while(sonKeys.length==1){
							var son = father[sonKeys[0]]
							delete grandpa[fatherKey]
							fatherKey += (isWindows?'\\':'/')+sonKeys[0]
							grandpa[fatherKey] = son
							father = son
							sonKeys = _.keys(father)
						}
						if(sonKeys.length>1){
							grandpa[fatherKey] = mergeTree(father)
						}
					}
					return tree
				}
				var tree = {}
				for(var j in fileList){
					var cur = tree
					var file = splitFilePath(fileList[j])
					var key = file[0]
					var i=0
					while((key in cur)&&(i<file.length)){
						cur = cur[key]
						i++
						key = file[i]
					}
					while(i<file.length){
						cur[key] = {}
						cur = cur[key]
						i++
						key = file[i]
					}
				}
				return mergeTree(tree)
			}

			function getEzpCommentStr(comments, frameRate){
				function fill2(num){
					return (num<10?'0':'') + num
				}
				function getTimeFromPos(frameRate, pos){
					var totalSeconds = parseInt(pos/frameRate)
					var hours = parseInt(totalSeconds/3600)
					var minutes = parseInt((totalSeconds%3600)/60)
					var seconds = parseInt(totalSeconds%60)
					var remain = pos - parseInt(totalSeconds*frameRate)
					return fill2(hours)+':'+fill2(minutes)+':'+fill2(seconds)+':'+fill2(remain)
				}
				var i=1
				var result = ''
				frameRate = parseFloat(frameRate).toFixed(2)
				for(var pos in comments){
					result += (fill2(i)+', '+ getTimeFromPos(frameRate,pos) + '   ' + comments[pos] + '\n')
					i++
				}
				return result
			}

			function extractEZP(data){
				addUserTag('帧率',data['帧率'])
				var ezpComment = getEzpCommentStr(JSON.parse(data.ezpComment), data['帧率'])
				var id = addUserTab('EZP内部Marker', ezpComment)
				$('#T-'+id+' div').hide()
				$('#T-'+id+' pre').removeClass('attached')

				if(data.materials){
					fileObj.dependFiles = data.materials
					for(var i in fileObj.dependFiles){
						addRelFile(fileObj.dependFiles[i])
					}
					addRelFileTree(data.materials)
				}

				// $('#correct-frame-rate').modal({
				// 	onApprove:function(){
				// 		var frameRate = $('input[name=frameRate]:checked').val()
				// 		if(frameRate=='other'){
				// 			frameRate = $('#frameRate-from-modal').val()
				// 		}
				// 		if(frameRate && frameRate!='other'){
							
				// 			fileObj['frameRate'] = frameRate
							
				// 			fileObj.ezpComment = ezpComment
							
				// 		}
				// 	}
				// }).modal('show')
			}

			function biggerInputArea(){
				$('#add-property-modal').modal({
					onApprove : function(){
						newUserProperty('fromModal')
					}
				}).modal('show');
			}
			function newUserPropertyFromEnter(event){
				if(event.keyCode == 13){
					newUserProperty();
				}
			}

			function newUserProperty(fromModal){
				function disLen(txt){
					return encodeURIComponent(txt).replace(/%..%..%../g, 'XX').length
				}
				var key,value;
				if(fromModal){
					key = $('#key-from-modal').val().trim()
					value = $('#value-from-modal').val().trim()
				}else{
					key = $('input[name=key]').val().trim()
					value = $('input[name=value]').val().trim()
				}
				if(key && value){
					if(key in fileObj){
						$('#modal-warn').modal('show')
					}else{
						fileObj[key] = value
						var lenKey = disLen(key)
						var lenValue = disLen(value)
						if(lenKey < 12 && lenValue < 16){
							addUserTag(key,value)
						}else if(fromModal && lenValue>40){
							addUserTab(key, value)
						}else{
							addUserProperty(key, value)
						}
					}
				}
			}

	    	function addSysTag(key, value){
	    		if($('#sys-labels').html().length<=4){
	    			$('#sys-labels').html('')
	    		}
	    		$('#sys-labels').append( _.template($('#sys-labels-tpl').html())({key:key,value:value}))
	    		$('.ui.label').popup()
	    	}

	    	function addSysProperty(key, value, detail){
	    		$('#sys-properties').append( _.template($('#sys-properties-tpl').html())({key:key,value:value,detail:detail}))
	    	}

	    	function addUserTab(key, value){
	    		var id = new Date().getTime()
	    		$('#user-tab-head').append( _.template($('#user-tab-head-tpl').html())({id:id, key:key}))
	    		$('#user-tab-head').parent().append( _.template($('#user-tab-tpl').html())({id:id, content:value}))
	    		// $('#user-tab-head .item').tab()
	    		$('.menu .item').tab()
	    		return id
	    	}

	    	function addUserTag(key, value){
	    		if($('#user-labels').html().length<=4){
	    			$('#user-labels').html('')
	    		}
	    		$('#user-labels').append( _.template($('#user-labels-tpl').html())({key:key,value:value}))
	    	}

	    	function delUserLabel(id){
	    		var key = $('#'+id).contents().get(0).nodeValue.trim()
	    		delete fileObj[key]
	    		$('#'+id).remove()
	    	}

	    	function delUserProperty(id){
	    		var key = $('#'+id+' td').html().trim()
	    		delete fileObj[key]
	    		$('#'+id).remove()
	    	}

	    	function delUserTab(id){
	    		var key = $('#TH-'+id).text().trim()
	    		delete fileObj[key]
	    		$('#TH-'+id).remove()
	    		$('#T-'+id).remove()
	    	}

	    	function editUserTab(id){
	    		var key = $('#TH-'+id).text().trim()
	    		$('#key-from-modal').val(key)
	    		$('#value-from-modal').val(fileObj[key])
	    		$('#add-property-modal').modal({
					onApprove : function() {
						var newKey = $('#key-from-modal').val().trim()
						var value = $('#value-from-modal').val().trim()
						if(newKey!=key){
							delete fileObj[key]
							$('TH-'+id).html(newKey)
						}
						fileObj[newKey] = value
						$('#T-'+id+' pre').text(value)
					}
	    		}).modal('show');
	    	}

	    	function addUserProperty(key, value){
	    		$('#user-properties').append( _.template($('#user-properties-tpl').html())({key:key,value:value}))
	    	}

	    	function addRelFile(path){
	    		$('#rel-files').append( _.template($('#rel-file-tpl').html())({name: getFileNameFromPath(path), path: getFilePath(path)} ));
	    	}

			function addRelFileTree(fileList){
				var tpl = _.template($('#rel-file-list-tpl').html())
				function fileTypeIcon(name){
					var ext = getFileExt(name).substring(1)
					switch(ext){
						case 'MOV':
						case 'AVI':
						case 'M2V':
						case 'MPA':
						case 'MPG': return 'file video outline'
						case 'ZIP':
						case 'RAR': return 'file archive outline'
						case 'MP3':
						case 'WMA':
						case 'WAV':
						case 'AC3':
						case 'AAC': return 'file audio outline'
						case 'DOC':
						case 'DOCX': return 'file word outline'
						case 'PDF': return 'file pdf outline'
						case 'JPEG':
						case 'JPG':
						case 'PNG':
						case 'BMP':
						case 'PSD': return 'file image outline'
						default: return 'file outline'
					}
				}
				function drawNode(root){
					var childContent = ''
					for(var child in root){
						var icon
						if(_.keys(root[child]).length==0){
							icon = fileTypeIcon(child)
						}else{
							icon = 'folder open disabled'
						}
						childContent += tpl({
							name: child,
							icon: icon,
							children: drawNode(root[child])
						})
					}
					return childContent
				}
				
				var tree = groupFileByFolderIter(fileList)
				$('#rel-files-lst').append( drawNode(tree) )
			}

			function setFileInfo(data){
				fileObj = data
				$('#path').html(getFilePath(data.path))
				$('#title').html(getFileNameFromPath(data.path))
				$('#header-below').css('margin-top', parseInt($('#header h2').outerHeight())+'px')
				$('#sys-labels').html('')
				addSysTag('文件大小', size2str(data.size))
				addSysTag('后缀名', getFileExt(data.path))
				addSysProperty('创建时间', moment(data.createTime).format('lll')+' '+getTimeZone()+' ('+moment(data.createTime).fromNow()+')')
				addSysProperty('最后修改时间', moment(data.lastModifiedTime).format('lll')+' '+getTimeZone()+' ('+moment(data.lastModifiedTime).fromNow()+')' )
				addSysProperty('唯一标识', hashToShort(data.hash), data.hash)
				if(data.md5head){
					addSysProperty('校验码', hashToShort(data.md5head), data.md5head)	
				}
				$('#comment').val(fileObj['comment'])
				if(data.ezpComment){
					extractEZP(data)
				}

				$('#commit-button').removeClass('disabled').addClass('green');
				$('#commit-button').click(function(){
					fileObj.comment = $('#comment').val()
					$('#loading').dimmer('show')
					$.ajax({
					    type: 'POST',
					    url: '/file/update.post',
					    data: JSON.stringify(fileObj),
					    success: function(data){
					    	console.log(data)
							window.close()
						},
					    contentType: "application/json",
					    dataType: 'text'
					});
				})
			}
	      	

		    $("document").ready(function(){
			    $('#header').sticky()
			    $('.ui.radio.checkbox').checkbox()
			    $.get('/file/'+document.location.href.slice(-128)+'/json', setFileInfo)
			});
			
		</script>

    </body>
</html>